package cdu.bbs.bbsv2.filter;

import cdu.bbs.bbsv2.domain.Admin;
import cdu.bbs.bbsv2.domain.User;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse)resp;
        HttpSession session = request.getSession();

        String path = request.getServletPath();
        if(path.contains("/admin")){
            if("/admin/login.jsp".equals(path) || "/admin/login.do".equals(path) ){
                filterChain.doFilter(req,resp);

            } else {
                Admin admin=(Admin) session.getAttribute("admin");
                if(admin != null){
                    filterChain.doFilter(req,resp);
                } else{
                    response.sendRedirect(request.getContextPath() + "/admin/login.jsp");
                }
            }
            return;
        }

        // 如果是用户
        if(path.contains("login") ||path.contains("register")){
            filterChain.doFilter(req,resp);
        }else {
            User user = (User) session.getAttribute("user");
            Admin admin=(Admin) session.getAttribute("admin");
            if(user != null ){
                filterChain.doFilter(req,resp);
            }else {
                response.sendRedirect(request.getContextPath() + "/login.jsp");
            }
            return;
        }


    }
}
